package cn.thornbird.orgsync.constraints;

import cn.thornbird.orgsync.entity.status.Status;
import cn.thornbird.orgsync.util.ReflectUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class NotNullCaseWhenValidator implements ConstraintValidator<NotNullCaseWhen, Object> {

    private String sourceFieldName;

    private short[] sourceFieldValues;

    private String[] targetFieldNames;

    @Override
    public void initialize(NotNullCaseWhen notNullCaseWhen) {
        this.sourceFieldName = notNullCaseWhen.source();
        this.sourceFieldValues = notNullCaseWhen.sourceValues();
        this.targetFieldNames = notNullCaseWhen.targets();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        boolean result = true;
        Object value = ReflectUtil.getValue(object, sourceFieldName);
        if (value != null && value instanceof Status) {
            for (int i = 0, count = targetFieldNames.length; i < count; i++) {
                if (sourceFieldValues[i] == ((Status) value).getValue()) {
                    Object targetFieldValue = ReflectUtil.getValue(object, targetFieldNames[i]);
                    if (targetFieldValue == null) {
                        result = false;
                        break;
                    }
                }
            }
        }
        return result;
    }

}
